<?php

	namespace app\job;

	use addons\wechat\library\Config;
	use ai\AiService;
	use app\common\model\goods\record\Token;
	use app\common\model\goods\record\Token as TokenRecordModel;
	use app\common\model\User;
	use EasyWeChat\Factory;
	use think\Exception;
	use think\Log;
	use think\queue\Job;

	class AI{
		public function reply(Job $job, $data){
			if ($job->attempts() > 1){
				$this->failed('reply',$data);
				$job->delete();
			}else{
				$ai = new AiService(config('site.dify'));
				$conversation_id = User::getConversationId($data['user_id']);
				$result = $ai->textReply($data['openid'], $data['message'], $conversation_id);
				User::setConversationId($data['user_id'], $result['conversation_id']);

				// 扣除token余额
				TokenRecordModel::change($data['user_id'], -$result['metadata']['usage']['total_tokens'], 'AI对话', json_encode($data['message']));

				// 返回客服消息
				$app = Factory::officialAccount(Config::load());
				$res = $app->customer_service->message($result['answer'])->to($data['openid'])->send();

				if($res['errcode'] == 0) $job->delete();
			}
		}

		public function failed($type, $data){
			Log::write('error:'.$type.' failed,data:'.json_encode($data), 'queue');
		}
	}